﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper.data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class DD_PushProcessInterfaceBusiness : DDInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption DD_Push;
        //创建成功返回的ID号
        public List<ReqProcessDTO> ProcessIDList { get; set; } = new List<ReqProcessDTO>();
        public DD_PushProcessInterfaceBusiness()
        {
            this.InterfaceName = "钉钉发起Q13-法歌帝验货流程";
            //索引字段
            this.MapFields = GetMapField("DD_Push");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            DD_Push = this.interfaceOption.Where(x => x.OperateType == "DD_Push").First();




            //查询执行前的事件
            //this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            ////查询执行中的事件
            //this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            ////查询执行中的事件
            //this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求前的事件
            this.BeforeNoQueryEvent += DD_PushProcessInterfaceBusiness_BeforeNoQueryEvent;
            //执行非查询请求中的事件
            this.OnNoQueryEvent += DD_PushProcessInterfaceBusiness_OnNoQueryEvent; ;
            //执行非查询请求后的事件
            this.AfterNoQueryEvent += DD_PushProcessInterfaceBusiness_AfterNoQueryEvent; ;
        }


        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void DD_PushProcessInterfaceBusiness_BeforeNoQueryEvent(object sender, DD_NoQueryEventArgs noQueryEventArgs)
        {
            //获取appId
            var key = JObject.Parse(DD_Push.TargetLoginData);
            noQueryEventArgs.UrlQuery.AppKey = key["appkey"].Value<string>();
            noQueryEventArgs.UrlQuery.AppSecret = key["appsecret"].Value<string>();
            noQueryEventArgs.UrlQuery.Corpid = key["corpid"].Value<string>();
            noQueryEventArgs.UrlQuery.Corpsecret = key["corpsecret"].Value<string>();
            //获取token
            JObject token = JObject.Parse(GetToken(noQueryEventArgs.UrlQuery));
            noQueryEventArgs.UrlQuery.Token = token["access_token"].ToString();
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void DD_PushProcessInterfaceBusiness_OnNoQueryEvent(object sender, DD_NoQueryEventArgs noQueryEventArgs)
        {
            if (!string.IsNullOrEmpty(noQueryEventArgs.UrlQuery.Token))
            {
                //获取拼接token的URL
                noQueryEventArgs.HttpClient.Url = $"{DD_Push.TargetUrl}?access_token={noQueryEventArgs.UrlQuery.Token}";
                var date = (DD_ReqDTO_Push)noQueryEventArgs.Data;
                //获取备注中的采购单号和用户
                var order = date.form_component_values.Where(x => x.name == "备注").First().value;
                //var user = date.form_component_values.Where(x => x.name == "申请人").First().value;
                noQueryEventArgs.CustomData = order;
                //获取审批表单的ID
                date.process_code = noQueryEventArgs.APINodes.Where(x => x.TargetField == "process_code").First().SourceField;
                //noQueryEventArgs.reqData = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, noQueryEventArgs.Data);
                noQueryEventArgs.reqData = date.ToJson();
            }
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void DD_PushProcessInterfaceBusiness_AfterNoQueryEvent(object sender, DD_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //将查询后的数据转换成对应格式的数据
                DD_ResDTO_Push result = (DD_ResDTO_Push)JsonConvert.DeserializeObject<DD_ResDTO_Push>(noQueryEventArgs.Result);
                if (result.errmsg == "ok")
                {
                    noQueryEventArgs.Success = true;
                    //noQueryEventArgs.Result = new List<object>() { result };
                    ProcessIDList.Add(new ReqProcessDTO() { process_instance_id = result.process_instance_id + "_split_" + noQueryEventArgs.CustomData.ToString() });
                    noQueryEventArgs.Page.Complete = true;
                }
                else
                {
                    noQueryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                noQueryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async Task ExecuteInterface()
        {

            try
            {

                //获取人员信息
                List<DD_UserDTO.User> users = this.SqlDb.GetListBySql<DD_UserDTO.User>("SELECT * FROM SD_DD_User");

                //获取采购需求
                OL_ProRequirementsInterfaceBusiness oL_ProRequirements = new OL_ProRequirementsInterfaceBusiness();
                oL_ProRequirements.Filters.Clear();
                oL_ProRequirements.Filters.Add(
                new OL_FilterDTO() { ControlId = "6826d9ada31d84c7f6348748", DataType = 2, SpliceType = 1, FilterType = 7, Value = "" }//是否检验为空的
            );
                oL_ProRequirements.Filters.Add(
                new OL_FilterDTO() { ControlId = "wfstatus", DataType = 2, SpliceType = 1, FilterType = 2, Value = "通过" }//流程状态为通过
            );
                oL_ProRequirements.Filters.Add(
                new OL_FilterDTO() { ControlId = "667d158cf97ad3fdfe460678", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }//采购订单不为空
            );
                //    oL_ProRequirements.Filters.Add(
                //    new OL_FilterDTO() { ControlId = "6830431ca31d84c7f6fa5c84", DataType = 26, SpliceType = 1, FilterType = 8, Value = "" }//采购员不为空
                //);

                oL_ProRequirements.Filters.Add(
                new OL_FilterDTO() { ControlId = "66d7fa4f1214257ad189fc1a", DataType = 26, SpliceType = 1, FilterType = 8, Value = "" }//供应商不为空
            );
                oL_ProRequirements.Filters.Add(
                new OL_FilterDTO() { ControlId = "682d6629a31d84c7f6b3b747", DataType = 2, SpliceType = 1, FilterType = 2, Value = "是" }//是否需要检验
            );
                //    oL_ProRequirements.Filters.Add(
                //    new OL_FilterDTO() { ControlId = "6825aef0a31d84c7f61e8c8e", DataType = 2, SpliceType = 1, FilterType = 2, Value = "外购" }//采购类型为外购
                //);

                List<OL_ProRequirements> sourceDatas = await oL_ProRequirements.QueryAsync<OL_ProRequirements>(oL_ProRequirements.queryOption, oL_ProRequirements.tableField, oL_ProRequirements.SqlDb);
                //只过滤外购类型的采购需求
                sourceDatas = sourceDatas.Where(x => !x.OrderType.IsNullOrEmpty() && x.OrderType == "外购").ToList();
                if (sourceDatas.Count > 0)
                {
                    sourceDatas.ForEach(x =>
                {
                    //创建人
                    List<Choice> choice = new List<Choice>();
                    if (!x.Creater.IsNullOrEmpty()) choice = x.Creater.ToObject<List<Choice>>();
                    if (choice.Count > 0 && !choice.IsNullOrEmpty()) x.Creater_s = choice[0].fullname;
                    //采购员
                    if (!x.Purchaser.IsNullOrEmpty()) choice = x.Purchaser.ToObject<List<Choice>>();
                    if (choice.Count > 0 && !choice.IsNullOrEmpty()) x.Purchaser = choice[0].fullname;

                    //SKU
                    List<AssTable> table = new List<AssTable>();
                    if (!x.SKU.IsNullOrEmpty()) table = x.SKU.ToObject<List<AssTable>>();
                    if (table.Count > 0 && !table.IsNullOrEmpty()) x.SKU_s = table[0].name;
                    //SSKU
                    //if (!x.SKU.IsNullOrEmpty()) table = x.SSKU.ToObject<List<AssTable>>();
                    //if (table.Count > 0 && !table.IsNullOrEmpty()) x.SSKU_s = table[0].name;
                    //采购订单
                    //if (!x.Order.IsNullOrEmpty()) table = x.Order.ToObject<List<AssTable>>();
                    //if (table.Count > 0 && !table.IsNullOrEmpty()) x.Order = table[0].name;

                });


                    //生成推送的钉钉的数据
                    List<DD_ReqDTO_Push> pushDatas = new List<DD_ReqDTO_Push>();
                    foreach (var item1 in sourceDatas.GroupBy(x => x.Order + x.Supplier))
                    {
                        var first = item1.First();
                        //创建人
                        var createrList = users.Where(x => item1.Select(x => x.Creater_s).Contains(x.name));
                        List<string> creaters = new List<string>();
                        if (!createrList.IsNullOrEmpty() && createrList.Count() > 0)
                        {
                            creaters = createrList.Select(x => x.userid).ToList();
                        }
                        else
                        {
                            creaters.Add("");
                        }
                        //采购员
                        var purchaserList = users.Where(x => x.name == first.Purchaser);
                        DD_UserDTO.User purchaser = new DD_UserDTO.User();
                        if (!purchaserList.IsNullOrEmpty() && purchaserList.Count() > 0)
                        {
                            purchaser = purchaserList.FirstOrDefault();
                        }
                        else
                        {
                            purchaser = users.Where(x => x.name == DD_Push.SourceData).First();
                        }


                        DD_ReqDTO_Push oreder = new DD_ReqDTO_Push();
                        if (!purchaser.IsNullOrEmpty() && !first.Order.IsNullOrEmpty())
                        {

                            //表头信息
                            DD_ReqDTO_Push.Component component1 = new DD_ReqDTO_Push.Component();
                            component1.name = "所属公司";
                            component1.value = "法歌帝";
                            oreder.form_component_values.Add(component1);

                            DD_ReqDTO_Push.Component component14 = new DD_ReqDTO_Push.Component();
                            component14.name = "采购类型";
                            component14.value = first.OrderType;
                            oreder.form_component_values.Add(component14);

                            DD_ReqDTO_Push.Component component11 = new DD_ReqDTO_Push.Component();
                            component11.name = "供方名称";
                            component11.value = first.Supplier.IsNullOrEmpty() ? "无" : first.Supplier;
                            oreder.form_component_values.Add(component11);

                            DD_ReqDTO_Push.Component component2 = new DD_ReqDTO_Push.Component();
                            component2.name = "申请人";
                            List<string> userID = new List<string>();
                            userID.Add(purchaser.userid);
                            component2.value = userID.ToJson();
                            oreder.originator_user_id = purchaser.userid;
                            oreder.form_component_values.Add(component2);


                            DD_ReqDTO_Push.Component component16 = new DD_ReqDTO_Push.Component();
                            component16.name = "需求人";

                            component16.value = creaters.ToJson();
                            //测试
                            //component2.value = "[\"012626185729943055\"]";
                            //oreder.originator_user_id = "012626185729943055";
                            oreder.form_component_values.Add(component16);



                            DD_ReqDTO_Push.Component component3 = new DD_ReqDTO_Push.Component();
                            List<long> depIDs = new List<long>();
                            var depID = purchaser.dept_id_list_s.Contains(",") ? purchaser.dept_id_list_s.Split(',').First().ToLong() : purchaser.dept_id_list_s.ToLong();
                            depIDs.Add(depID);
                            component3.name = "所在部门";
                            component3.value = depIDs.ToJson();
                            oreder.dept_id = depID;
                            //测试
                            if (purchaser.name == "王旺") oreder.dept_id = 962841142;
                            oreder.form_component_values.Add(component3);

                            DD_ReqDTO_Push.Component component4 = new DD_ReqDTO_Push.Component();
                            component4.name = "备注";
                            component4.value = first.Order;
                            oreder.form_component_values.Add(component4);

                            //明细
                            DD_ReqDTO_Push.Component component5 = new DD_ReqDTO_Push.Component();
                            component5.name = "产品验货需求明细";

                            List<List<DD_ReqDTO_Push.Component>> table = new List<List<DD_ReqDTO_Push.Component>>();
                            foreach (var item2 in item1)
                            {
                                //每一行数据
                                List<DD_ReqDTO_Push.Component> row = new List<DD_ReqDTO_Push.Component>();

                                DD_ReqDTO_Push.Component component15 = new DD_ReqDTO_Push.Component();
                                component15.name = "检验类型";
                                component15.value = item2.CheckedResult == "不合格" ? "不合格复检" : "首次检验";
                                row.Add(component15);

                                DD_ReqDTO_Push.Component component13 = new DD_ReqDTO_Push.Component();
                                component13.name = "产品类型";
                                component13.value = item2.PrdType.IsNullOrEmpty() ? "无" : item2.PrdType;
                                row.Add(component13);

                                DD_ReqDTO_Push.Component component6 = new DD_ReqDTO_Push.Component();
                                component6.name = "成品编码";
                                component6.value = item2.SKU_s.IsNullOrEmpty() ? "无" : item2.SKU_s;
                                row.Add(component6);

                                DD_ReqDTO_Push.Component component17 = new DD_ReqDTO_Push.Component();
                                component17.name = "SSKU";
                                component17.value = item2.SSKU.IsNullOrEmpty() ? "无" : item2.SSKU;
                                row.Add(component17);

                                DD_ReqDTO_Push.Component component7 = new DD_ReqDTO_Push.Component();
                                component7.name = "规格型号";
                                component7.value = item2.PrdName.IsNullOrEmpty() ? "无" : item2.PrdName;
                                row.Add(component7);

                                DD_ReqDTO_Push.Component component8 = new DD_ReqDTO_Push.Component();
                                component8.name = "品牌";
                                component8.value = item2.Brand.IsNullOrEmpty() ? "无" : item2.Brand;
                                row.Add(component8);

                                DD_ReqDTO_Push.Component component9 = new DD_ReqDTO_Push.Component();
                                component9.name = "订单号/PI";
                                component9.value = item2.Order.IsNullOrEmpty() ? "无" : item2.Order;
                                row.Add(component9);

                                DD_ReqDTO_Push.Component component10 = new DD_ReqDTO_Push.Component();
                                component10.name = "预计验货数量";
                                component10.value = item2.Qty;
                                row.Add(component10);

                                DD_ReqDTO_Push.Component component12 = new DD_ReqDTO_Push.Component();
                                component12.name = "ID";
                                component12.value = item2.RowId.IsNullOrEmpty() ? "无" : item2.RowId;
                                row.Add(component12);
                                table.Add(row);
                            }
                            component5.value = table;
                            oreder.form_component_values.Add(component5);
                        }

                        pushDatas.Add(oreder);
                    }

                    //将没有单据编号的采购需求发起钉钉审批
                    await this.ExecuteNoQuery<DD_ReqDTO_Push>(pushDatas, this.DD_Push, this.SqlDb);

                    //发起成功后更新原来单上的钉钉单据编号
                    if (ProcessIDList.Count > 0)
                    {
                        DD_ProcessInterfaceBusiness query = new DD_ProcessInterfaceBusiness();
                        foreach (var item1 in ProcessIDList)
                        {
                            //获取订单对应的钉钉审批单ID[0]，订单号[1]
                            var group = item1.process_instance_id.Split("_split_");
                            //var user = users.Where(x => group[2].Contains(x.userid));
                            item1.process_instance_id = group[0];
                            //获取已发起成功的审批单号
                            var p = await query.QueryProcess(item1);
                            //查询单号相同相同的采购订单，将钉钉单号更新上去
                            var order = sourceDatas.Where(x => x.Order == group[1]);
                            if (order != null)
                            {
                                order.ForEach(x =>
                                {
                                    //有可能此采购需求已经存在单号，所以需要将单号拼接
                                    x.CheckNumber = x.CheckNumber.IsNullOrEmpty() ? p.First().process_instance.business_id : x.CheckNumber + "，" + p.First().process_instance.business_id;
                                    x.CheckState = "已发起";
                                });
                            }
                        }

                        List<OL_RowDTO> updataData = oL_ProRequirements.ConvertOL_Row(sourceDatas, oL_ProRequirements.tableField);//需要更新的数据集合
                        oL_ProRequirements.ExecuteNoQuery<OL_RowDTO>(updataData, oL_ProRequirements.upDateOption, oL_ProRequirements.SqlDb);//执行更新
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 接口发送请求获取TOKEN
        /// </summary>
        /// <param name="ol_key"></param>
        /// <returns></returns>
        public string GetToken(DD_UrlQuery query)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Method = "GET";
            // 设置请求参数
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat($"https://oapi.dingtalk.com/gettoken?");
            sb.AppendFormat($"appkey={query.AppKey}&");
            sb.AppendFormat($"appsecret={query.AppSecret}&");
            sb.AppendFormat($"corpid={query.Corpid}&");
            sb.AppendFormat($"corpsecret={query.Corpsecret}");
            httpClient.Url = sb.ToString();
            string sysReportResul1t = httpClient.Request();
            if (!sysReportResul1t.IsNullOrEmpty())
            {
                return sysReportResul1t;

            }
            else
            {
                return "";

            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
